<?

/**
 * $Id: Utils.class.php 968 2008-07-29 10:47:29Z dakl $
 *
 * Copyright (c) 2002-2008 Formix www.formix.pl
 * Ten plik �r�d�owy jest w�asno�ci� firmy Formix.
 *
 * Klasa statyczna z funkcjami pomocniczymi
 *
 */
class Utils {

	/**
	 * Funkcja do wyświetlania tablic asocjacyjnych, obiektów itd.
	 * Zastępuje funkcje array_display
	 *
	 * @param array, object $p_array Tablica lub obiekt do wyświetlenia
	 */
	public static function ArrayDisplay($p_array) {
		print "<div style='background-color: white; color: black; text-align: left; font-size: 1.5em'><pre>";
		print_r($p_array);
		print "</pre></div>";
	}


	public static function GetArrayValuesRecursive($array)
{
    $arrayValues = array();

    foreach ($array as $value)
    {
        if (is_scalar($value) OR is_resource($value))
        {
             $arrayValues[] = $value;
        }
        elseif (is_array($value))
        {
             $arrayValues = array_merge($arrayValues, self::GetArrayValuesRecursive($value));
        }
    }

    return $arrayValues;
}

	/**
	 * Stara funkcja array_display - działa prawidłowo w wersji PHP 4
	 *
	 * @param array, object $p_array Tablica lub obiekt do wyświetlenia
	 * @param int $user_defined I don't know ;)
	 */
	public static function ArrayDisplayOld($array_name, $user_defined = 0) {
		$indexBreak = 0;
		if (!isset($array_name)) {
			print("<P><B>TABLICA JEST PUSTA</B><P>\n");
		} else {
			print("<table border=1 cellspacing=1 style=\"font-family: Verdana; font-size: 10 pt;\" width=\"100%\">\n");
			print("<tr><th colspan=2 bgcolor=\"#DDDDDD\">" . $array_name . "</TR>\n");
			//	for (reset($array_name); (strcmp(($key=key($array_name)) ,"")); next($array_name)){
			while (list($key, $value) = each($array_name)) {
				if (strcmp($key, "GLOBALS") == 0)
					$user_defined = 0;
				if ($user_defined == 1)
					continue;
				if ((is_array($value) || is_object($value)) && (strcmp($key, "GLOBALS") != 0)) {
					print("<tr><td bgcolor=\"#66ccff\" width=10><font style=\"font-size:9;\">" . substr(gettype($key), 0, 3) . "</font>&gt;" . str_replace(" ", "&nbsp;", $key) . "&lt;<font style=\"font-size:9;\">" . (is_object($array_name) ? 'b.d.' : count($array_name[$key])) . "</font><td bgcolor=\"#66ccff\">");
					Utils::ArrayDisplayOld($value);
					print ("</tr>\n");
				} else {
					print("<tr><td bgcolor=\"#66bbff\" width=10><font style=\"font-size:9;\">" . substr(gettype($key), 0, 3) . "</font>&gt;" . str_replace(" ", "&nbsp;", $key) . "<font>&lt;</font>");
					print("<td bgcolor=\"#f5a5e8\"><font style=\"font-size:9;\">" . substr(gettype($value), 0, 3) . "</font>&gt;" . str_replace(" ", "&nbsp;", $value) . "&lt;</TR>\n");
				}
				if (++$indexBreak > 1000) {
					break;
				}
			}
			print("</TABLE >\n");
			@reset($array_name);
		}
	}

	/**
	 * Przeszukiwanie tablicy na podstawie zadanych tekst�w
	 *
	 * @param Array $array
	 * @param string $keySearchStart
	 * @param string $keySearchEnd
	 * @return int
	 */
	public static function GetArrayKeyNumberDifference($array, $keySearchStart, $keySearchEnd) {
		$index = 0;
		foreach ($array as $key => $value) {
			if ($key == $keySearchStart) {
				$indexStart = $index;
			}
			if ($key == $keySearchEnd) {
				$indexEnd = $index;
				break; // przerywamy bo nie mamy czego szukac
			}
			$index++;
		}
		$difference = $indexEnd - $indexStart;
		return $difference;
	}

	/**
	 * Zwraca rozszerzenie pliku na podstawie nazwy
	 *
	 * @param string $fileName
	 * @return string
	 */
	public static function FileExtFromName($fileName) {
		$array = explode('.', $fileName);
		$ext = $array[count($array) - 1];
		return $ext;
	}

	/**
	 * Zwraca nazwe pliku bez rozszerzenia
	 *
	 * @param string $fileName
	 * @return string
	 */
	public static function FileNameFromName($fileName) {
		$array = explode('.', $fileName);
		unset($array[count($array) - 1]);
		$fileName = implode('.', $array);
		return $fileName;
	}

	/**
	 * Wykonuje redirect
	 *
	 * @param string $url
	 */
	public static function Redirect($url, $error =false) {
		$url = str_replace('&amp;', '&', $url);
		header("HTTP/1.1 $error");
		header("Location: " . $url);
		exit();
	}

	/**
	 * Porz�dkuje entery (zwaraca tekst z enterami w zadanej postaci)
	 *
	 * @param string $p_text
	 * @param string $p_enter
	 * @return string
	 */
	function GetSaveEnterInText($p_text, $p_enter = null) {
		$enter = is_null($p_enter) ? chr(13) : $p_enter;
		$text = $p_text;

		$text = str_replace("\r\n", "\n", $text);
		$text = str_replace("\r", "", $text);
		$text = str_replace("\n", $enter, $text);

		return $text;
	}

	/**
	 * Wy�wietla zapytania (funcja do debugowania)
	 *
	 */
	function DisplayQueries() {
		echo count($_SESSION['queries']) . '<br>';
		sort($_SESSION['queries']);
		Utils::ArrayDisplayOld($_SESSION['queries']);
		unset($_SESSION['queries']);
	}

	public static function RemovePolish($string) {
		$letters = array(':' => '-', ' ' => '-', 'ę' => 'e', 'ó' => 'o', 'ą' => 'a', 'ś' => 's', 'ł' => 'l', 'ż' => 'z', 'ź' => 'z', 'ć' => 'c', 'ń' => 'n', 'ę' => 'e', 'Ó' => 'O', 'Ą' => 'A', 'Ś' => 'S', 'Ł' => 'L', 'Ż' => 'Z', 'Ź' => 'Z', 'Ć' => 'C', 'Ń' => 'N');
		$string = strtr($string, $letters);
		foreach ($letters as $letters => $replacement) {
			$string = str_replace($letters, $replacement, $string);
		}
		return strtolower($string);
	}

	public static function RemovePolishNoToLower($string) {
		$letters = array(':' => '-', ' ' => '-', 'ę' => 'e', 'ó' => 'o', 'ą' => 'a', 'ś' => 's', 'ł' => 'l', 'ż' => 'z', 'ź' => 'z', 'ć' => 'c', 'ń' => 'n', 'ę' => 'e', 'Ó' => 'O', 'Ą' => 'A', 'Ś' => 'S', 'Ł' => 'L', 'Ż' => 'Z', 'Ź' => 'Z', 'Ć' => 'C', 'Ń' => 'N');
		$string = strtr($string, $letters);
		foreach ($letters as $letters => $replacement) {
			$string = str_replace($letters, $replacement, $string);
		}
		return $string;
	}

	public static function TextToUrl($string) {
		$letters = array(Config::Get('URL_DELIMITER') => '-', '/' => '', ':' => '-', ' ' => '-', 'ę' => 'e', 'ó' => 'o', 'ą' => 'a', 'ś' => 's', 'ł' => 'l', 'ż' => 'z', 'ź' => 'z', 'ć' => 'c', 'ń' => 'n', 'ę' => 'e', 'Ó' => 'O', 'Ą' => 'A', 'Ś' => 'S', 'Ł' => 'L', 'Ż' => 'Z', 'Ź' => 'Z', 'Ć' => 'C', 'Ń' => 'N');
		$string = strtr($string, $letters);
		foreach ($letters as $letters => $replacement) {
			$string = str_replace($letters, $replacement, $string);
		}
		return urlencode(strip_tags($string));
	}

	public static function AddSlashes($string) {
		if (get_magic_quotes_gpc() == 1) {
			return $string;
		} else {
			return addslashes($string);
		}
	}

	public static function TextToTitle($string) {
		$string = str_replace('"', '', (strip_tags($string)));
		return $string;
	}

	/**
	 * Zamienia polskie znaki zakodowane utf pobrane z adresu url(param) na polskie znaki :)
	 *
	 */
	function url2pl($text) {
		// $text = str_replace("", '/', $text);
		$text = str_replace("%2F", '/', $text);
		$text = str_replace("\xC4\x85", '�', $text);
		$text = str_replace("\xC4\x84", '�', $text);
		$text = str_replace("\xC4\x87", '�', $text);
		$text = str_replace("\xC4\x86", '�', $text);
		$text = str_replace("\xC4\x99", '�', $text);
		$text = str_replace("\xC4\x98", '�', $text);
		$text = str_replace("\xC5\x82", '�', $text);
		$text = str_replace("\xC5\x81", '�', $text);
		$text = str_replace("\xC3\xB3", '�', $text);
		$text = str_replace("\xC3\x93", '�', $text);
		$text = str_replace("\xC5\x9B", '�', $text);
		$text = str_replace("\xC5\x9A", '�', $text);
		$text = str_replace("\xC5\xBC", '�', $text);
		$text = str_replace("\xC5\xBB", '�', $text);
		$text = str_replace("\xC5\xBA", '�', $text);
		$text = str_replace("\xC5\xB9", '�', $text);
		$text = str_replace("\xc5\x84", '�', $text);
		$text = str_replace("\xc5\x83", '�', $text);

		return $text;
	}

	function specjalSearchSing($text) {
		$text = str_replace("%2F", '%252F', $text);
		$text = str_replace("/", '%252F', $text);

		return $text;
	}

	public function cleanUrl($text) {
		$code_entities_match = array(' ', '--', '&quot;', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '{', '}', '|', ':', '"', '<', '>', '?', '[', ']', '\\', ';', "'", ',', '.', '/', '*', '+', '~', '`', '=');
		$code_entities_replace = array('-', '-', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
		$text = str_replace($code_entities_match, $code_entities_replace, $text);

		return $text;
	}

	public function cleanUrlSpaces($text) {
		$code_entities_match = array(' ', '--', '&quot;', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '{', '}', '|', ':', '"', '<', '>', '?', '[', ']', '\\', ';', "'", ',', '.', '/', '*', '+', '~', '`', '=');
		$code_entities_replace = array(' ', '-', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
		$text = str_replace($code_entities_match, $code_entities_replace, $text);

		return $text;
	}

	/**
	 * Pomocnicza f sortuj�ca
	 *
	 */
	public static function sortIt($objA, $objB, $key = 'count') {
		if ($objA[$key] == $objB[$key])
			return 0;
		return ($objA[$key] > $objB[$key]) ? -1 : 1;
	}

	/**
	 * Pomocnicza f sortuj�ca
	 *
	 */
	public static function sortByQO($objA, $objB) {
		self::sortIt($objA, $objB, 'queue_order');
	}

	/**
	 * Rozpoczyna mpomiar czasu
	 *
	 */
	public static function TimerStart() {
		// Rozpoczynamy pomiar czasu wykonywania skryptu
		$mtime = microtime();
		$mtime = explode(" ", $mtime);
		$mtime = $mtime[1] + $mtime[0];
		$starttime = $mtime;
		// -->
	}

	/**
	 * Konczy pomiar czasu
	 *
	 * @return string
	 */
	public static function TimerEnd() {
		// Konczymy pomiar czasu wykonywania skryptu
		$mtime = microtime();
		$mtime = explode(" ", $mtime);
		$mtime = $mtime[1] + $mtime[0];
		$endtime = $mtime;
		$totaltime = ($endtime - $starttime);
		return $totaltime;
	}

	/**
	 * Zapisuje sortowanie dla podanej tabeli 
	 *
	 * @param array $p_arraySort tablica id'k�w
	 * @param string $sortColumn kolumna sortowania 	
	 * @param string $table tabla sortowania 
	 * @param string $idColumn po jakim id'ku sorujemy
	 */
	public static function SaveSort($arraySort, $sortColumn, $table, $idColumn) {
		$db = Registry::Get('db');
		if (count($arraySort)) {
			foreach ($arraySort as $id => $value) {
				$sql = 'UPDATE ' . $table . ' SET ' . $sortColumn . '=' . $value . ' WHERE ' . $idColumn . ' = ' . $id;
				//Utils::ArrayDisplay($sql);
				$db->execute($sql);
			}
		}
	}

	/**
	 * Filtr danych XSS
	 *
	 * @param string $val
	 * @return string
	 */
	public static function RemoveXss($val) {

		//		$val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);

		$search = 'a�bc�de�fghijkl�mno�pqrs�tuvwxyz��';
		$search .= 'A�BC�DE�FGHIJKL�MNO�PQRS�TUVWXYZ��';
		$search .= '1234567890!@#$%^&*()';
		$search .= '~`";:?+/={}[]-_|\'\\';
		for ($i = 0; $i < strlen($search); $i++) {

			$val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val);

			$val = preg_replace('/(&#0{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val);
		}

		$ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'base');
		$ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
		$htmlStart = '/\"\s*>/';

		$ra = array_merge($ra1, $ra2);

		$found = true;
		while ($found == true) {
			$val_before = $val;
			for ($i = 0; $i < sizeof($ra); $i++) {
				$pattern = '/';
				for ($j = 0; $j < strlen($ra[$i]); $j++) {
					if ($j > 0) {
						$pattern .= '(';
						$pattern .= '(&#[xX]0{0,8}([9ab]);)';
						$pattern .= '|';
						$pattern .= '|(&#0{0,8}([9|10|13]);)';
						$pattern .= ')*';
					}
					$pattern .= $ra[$i][$j];
				}
				$pattern .= '/i';
				$replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2);
				$val = preg_replace($pattern, $replacement, $val);
				$val = preg_replace($htmlStart, "", $val);
				if ($val_before == $val) {

					$found = false;
				}
			}
		}

		return $val;
	}


	/**
	 * Zwraca sliczna date
	 *
	 * @param string $datetime
	 * @return string
	 */
	public static function NiceDate($datetime, $noShort = false, $format = null, $time_format = null) {
		echo "param: $datetime";
		$date = strtotime($datetime);
		if (!$date) {
			$date = (int) $datetime;
		}

		$now = time();

		$out = '';

		if ($format == null)
			$format = Registry::Get('DATE_SHORT_FORMAT');

		if ($time_format == null)
			$time_format = Registry::Get('TIME_DEFAULT_FORMAT');

		if (!$noShort) {
			if (date(Registry::Get('DATE_SHORT_FORMAT'), $date) == date(Registry::Get('DATE_SHORT_FORMAT'), $now)) {
				$out = "Dzisiaj, " . strftime($time_format, $date);
			} else if (date(Registry::Get('DATE_SHORT_FORMAT'), $date) == date(Registry::Get('DATE_SHORT_FORMAT'), $now - 86400)) {
				$out = "Wczoraj, " . strftime($time_format, $date);
			} else if (stristr(PHP_OS, "WIN")) {
				$out = ucfirst(iconv("CP1250", "ISO-8859-2", strftime($format, $date)));
			} else {
				$out = ucfirst(strftime($format, $date));
			}
		} else {
			if (stristr(PHP_OS, "WIN")) {
				$out = ucfirst(iconv("CP1250", "ISO-8859-2", strftime($format, $date)));
			} else {
				$out = ucfirst(strftime($format, $date));
			}
		}

		return $out;
	}

	/**
	 * Pod�wietla s�owa wyst�puj�ce w tytule i tre�ci.
	 * Nale�y przekaza� mu DataObject.
	 * Fields - pola po przecinku, w kt�rych ma by� wyr�nione slowo wyszukania.
	 * $hlBegin - tekst wstawiony przed szukabym s�owem
	 * $hlEnd - tekst wstawiony po szukabym s�owie
	 *
	 * @param DataObject $array
	 * @param string $search
	 * @param string $fields
	 * @param string $hlBegin
	 * @param string $hlEnd
	 */
	public static function HighlightText(&$array, $search, $fields = 'Title,Text,Tag', $hlBegin = HL_BEGIN, $hlEnd = HL_END) {
		$search = strtolower($search);
		$replace = "$hlBegin$search$hlEnd";

		$field = explode(',', $fields);
		if (is_array($array)) {
			foreach ($array as $obj) {
				for ($i = 0; $i < count($field); $i++) {
					if ($field[$i] == 'Tag') {
						$methodGet = "Get" . trim($field[$i]);
						$methodSet = "Set" . trim($field[$i]);

						$value = $obj->$methodGet();
						$arrayValue = explode(',', $value);
						$done = array();
						foreach ($arrayValue as $tagObj) {

							if (strtolower($tagObj) == strtolower($search)) {
								$tagObj = $replace;
								array_unshift($done, $tagObj);
							} else {
								$done[] = $tagObj;
							}
						}

						$value = implode(',', $done);
						$obj->$methodSet($value);
					} else {
						$methodGet = "Get" . trim($field[$i]);
						$methodSet = "Set" . trim($field[$i]);

						$value = $obj->$methodGet();
						$obj->$methodSet(str_ireplace($search, $replace, $value));
					}
				}
			}
		} else {
			for ($i = 0; $i < count($field); $i++) {
				if ($field[$i] == 'Tag') {
					$methodGet = "Get" . trim($field[$i]);
					$methodSet = "Set" . trim($field[$i]);

					$value = $obj->$methodGet();
					$arrayValue = explode(',', $value);
					$done = array();
					foreach ($arrayValue as $tagObj) {

						if (strtolower($tagObj) == strtolower($search)) {
							$tagObj = $replace;
							array_unshift($done, $tagObj);
						} else {
							$done[] = $tagObj;
						}
					}

					$value = implode(',', $done);
					$obj->$methodSet($value);
				} else {
					$methodGet = "Get" . trim($field[$i]);
					$methodSet = "Set" . trim($field[$i]);

					$value = $obj->$methodGet();
					$obj->$methodSet(str_ireplace($search, $replace, $value));
				}
			}
		}
	}

	/**
	 * Zwraca dat� - miesi�c za kt�ry przyznana zosta�a nagroda.
	 *
	 */
	public static function AwardDate() {

		$month = (int) date('m');
		$year = (int) date('Y');

		//Od 21 nagrody przyznajemy za obecny miesiac, wcze�niej za miniony
		if ((int) date('d') < 21) {
			$month--;

			if ($month == 0) {
				$month = 12;
				$year--;
			}
		}

		return $year . $month . "01";
	}

	/**
	 * counts elements of an multidimensional array
	 *
	 * @param array $array Input Array
	 * @param int $limit dimensions that shall be considered (-1 means no limit )
	 * @return int counted elements
	 */
	public static function Multicount($array, $limit = -1) {
		$cnt = 0;
		$limit = $limit > 0 ? (int) $limit : -1;
		$arrs[] = $array;
		for ($i = 0; isset($arrs[$i]) && is_array($arrs[$i]); ++$i) {
			foreach ($arrs[$i] as $value) {
				if (!is_array($value))
					++$cnt;
				elseif ($limit == -1 || $limit > 1) {
					if ($limit > 1)
						--$limit;
					$arrs[] = $value;
				}
			}
		}
		return $cnt;
	}

	/**
	 * Konwertuje tablicę do formatu jSon'a.
	 *
	 * @param array $array
	 * @return string
	 */
	public static function Array2Json($array) {
		$output = "{";

		foreach ($array as $key => $val) {
			if (is_array($val)) {
				$output .= "\"" . $key . "\" : [" . Array2Json($val) . "],";
			} else {
				$output .= "\"" . $key . "\" : \"" . $val . "\",";
			}
		}

		$output .= "}";
		return $output;
	}

	/**
	 * funkcja wypisujaca js wypisujacego adres email
	 *
	 * @param <type> $email - adres email
	 * @param <type> $cssClass  - klasa css dla linka
	 */
	public static function jsEmail($email, $cssClass = null) {
		$s = '<script type="text/javascript">';

		$emailArray = explode("@", $email);
		if ($cssClass != null)
			$s .= 'document.write(\'<a class="' . $cssClass . '" href="mai\');';
		else
			$s .= 'document.write(\'<a href="mai\');';

		$s .= 'document.write(\'lto:' . $emailArray[0] . '\');';
		$s .= 'document.write(\'@\');';
		$s .= 'document.write(\'' . $emailArray[1] . '\');';
		$s .= 'document.write(\'">\');';

		$s .= 'document.write(\'' . $emailArray[0] . '\');';
		$s .= 'document.write(\'@\');';
		$s .= 'document.write(\'' . $emailArray[1] . '\');';

		$s .= 'document.write(\'</a>\');';
		$s .= '</script>';

		return $s;
	}

	/**
	 * funkcja przypisuje cyfrom z lancucha wartosci literowe (na potrzeby LUCENE)
	 * @param string $var
	 * @return string
	 */
	public static function codeIntToChar($var) {
		$out = null;
		//var_dump($var);

		$lenght = strlen($var);
		$var = (string) $var;

		for ($i = 0; $i < $lenght; $i++) {
			if (in_array($var[$i], array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))) {
				$out .= chr(107 + $var[$i]);
			} else {
				$out .= $var[$i];
			}
		}
		//var_dump($out);
		//if($lenght < 3) {
		//	$out = 'zxc'.$out;
		//}
		return $out;
	}

	public static function codeCharToInt($var) {
		$out = null;
		$lenght = strlen($var);
		$var = (string) $var;
		for ($i = 0; $i < $lenght; $i++) {
			$ord = ord($var[$i]) - 107;
			$out .= $ord;
		}
		//TODO - obsluga dla mniejszych liczb niz 3 cyfry
		if ($lenght < 3) {
			$out = 'zxc' . $out;
		}
		return $out;
	}

	/**
	 * Metoda tworzy katalogi
	 *
	 * @param string $dir sciezka katalog�w
	 * @param int $mode prawa zapisu
	 * @param bool $recursive czy ma tworzy� katalogi rekursywnie
	 * @return bool
	 */
	public static function Mkdirs($dir, $mode = 0777, $recursive = true) {
		if (is_null($dir) || $dir === "") {
			return FALSE;
		}
		if (is_dir($dir) || $dir === DIRECTORY_SEPARATOR) {
			return TRUE;
		}
		if (PhotoDAL::mkdirs(dirname($dir), $mode, $recursive)) {
			return mkdir($dir, $mode);
		}
		return FALSE;
	}

	public static function dateDiff($date1, $date2) {
		//$date1  today, or any other day
		//$date2  date to check against

		$d1 = explode(" ", $date1);
		$y1 = $d1[0];
		$m1 = $d1[1];
		$d1 = $d1[2];

		$d2 = explode(" ", $date2);
		$y2 = $d2[0];
		$m2 = $d2[1];
		$d2 = $d2[2];

		$date1_set = mktime(0, 0, 0, $m1, $d1, $y1);
		$date2_set = mktime(0, 0, 0, $m2, $d2, $y2);

		return(round(($date2_set - $date1_set) / (60 * 60 * 24)));
	}

	public static function convertSecondToArray($secs)
	{
			$units = array(
					"2"     =>   24*3600,
					"3"		=>      3600,
					"4"		=>        60,
					"5"		=>         1,
			);

			foreach ( $units as &$unit ) {
				$quot  = intval($secs / $unit);
				$secs -= $quot * $unit;
				$unit  = $quot;
			}
			return $units;
	}


	public static function convertArrayToDate($units)
	{
		if($units[2] > 0)
			return 	 $units[2] . ($units[2] > 1 ? " dni" : " dzień");
		else if($units[3] > 0)
			return 	 $units[3] . ($units[3] > 1 ? ($units[3]%10 >=2 && $units[3]%10 <= 4 ? " godziny" : " godzin" ) : " godzina");
		else if($units[4] > 0)
		{
			return 	 $units[4] . ($units[4] > 1 ? ($units[4]%10 >=2 && $units[4]%10 <= 4 ? " minuty" : " minut" ) : " minuta");
		}
		else if($units[5] > 0)
		{
			return 	 $units[5] . ($units[5] > 1 ? ($units[5]%10 >=2 && $units[5]%10 <= 4 ? " sekundy" : " sekund" ) : " sekunda");
		}

	}

	public static function convertSecondToHumanReadableString($secs)
	{
			$units = array(
					"1"   => 7*24*3600,
					"2"    =>  24*3600,
					"3"   => 3600,
					"4" =>     60,
					"5" =>    1,
			);

		// specifically handle zero
			if ( $secs == 0 ) return "0 seconds";

			$s = "";

			foreach ( $units as $key => $divisor ) {
					if ( $quot = intval($secs / $divisor) ) {
							$s .= "$quot ";

							//dodanie
							switch($key)
							{
								case 1:
									$s .= (abs($quot) > 1 ?  (abs($quot)%10 >=2 && abs($quot)%10 <= 4 ? "tygodnie" : "tygodni" ) : "tydzień") . ", ";
								break;
								case 2:
									$s .= (abs($quot) > 1 ? "dni" : "dzień") . ", ";
								break;
								case 3:
									$s .= (abs($quot) > 1 ?  (abs($quot)%10 >=2 && abs($quot)%10 <= 4 ? "godziny" : "godzin" ) : "godzina") . ", ";
								break;
								case 4:
									$s .= (abs($quot) > 1 ?  (abs($quot)%10 >=2 && abs($quot)%10 <= 4 ? "minuty" : "minut" ) : "minuta") . ", ";
								break;
								case 5:
									$s .= (abs($quot) > 1 ?  (abs($quot)%10 >=2 && abs($quot)%10 <= 4 ? "sekundy" : "sekund" ) : "sekunda") . ", ";
								break;
							}
							$secs -= $quot * $divisor;
					}
			}

			return substr($s, 0, -2);
	}
	
	public static function MultiImplode($glue, $pieces, $multiGlue = null) {
		if(!is_array($pieces))
		{
			$pieces = array($pieces);
		}
		$first = array_shift($pieces);

		if (!$multiGlue) {
			$multiGlue = $glue;
		}

		$ret = (is_array($first) ? self::MultiImplode($glue, $first, $multiGlue) : $first);

		foreach ($pieces as $item) {
			if (is_array($item)) {
				$ret .= $multiGlue . '' . self::MultiImplode($glue, $item);
			} else {
				$ret .= $glue . $item;
			}
		}

		return $ret;
	}

	public static function CleanString($str) {
		return str_replace(array('\"', "R11;", "R22;", "R21;", "R30;", "R17;"), array('"', '-', '&rdquo;', '&bdquo;', '', ''), $str);
	}

	public static function DisplayBackTrace($backtrace) {
		$backtrace = array_map(create_function('$a', 'return array($a["line"], $a["file"], $a["function"]);'), $backtrace);
		var_dump($backtrace);
	}

	/*
	 * Zamienia " na &quot;, < na &lt; , > &gt;
	 */

	public static function SaveInput($string, $type = 'input') {

		$patterns = array('/"/');
		$replacements = array('&quot;');

		if ($type == 'textarea') {
			$patterns = array('/"/', '/<textarea>/', '/<\/textarea>/');
			$replacements = array('&quot;', '&lt;textarea&gt;', '&lt;/textarea&gt;');
		}
		$str = preg_replace($patterns, $replacements, $string);
		return $str;
	}

	/*
	 * Sortowanie
	 *
	 * array $param
	 * array $fields - para 'nazwa z bazy' => 'nazwa wyswietlana'
	 * string $session - identyfikacja zmiennych w sesji
	 * string $defaultField
	 * string $defaultOrder
	 *
	 */

	public static function SortList($param, $fields, $session, $defaultField = 'kolejnosc', $defaultOrder = 'ASC') {
		$field = $fields[$defaultField];
		$order = $defaultOrder;

		if (isset($param['sortuj'])) {
			foreach ($fields as $dbfield => $appfield) {
				if ($dbfield == $param['sortuj']) {
					$field = $appfield;
				}
			}
			$oorder = SessionProxy::GetValue('__sort_' . $session . '_index_order__');
			if ($oorder == 'ASC') {
				$order = 'DESC';
			}
			SessionProxy::SetValue('__sort_' . $session . '_index_order__', $order);
			SessionProxy::SetValue('__sort_' . $session . '_index_field__', $field);
		} else {
			$oorder = SessionProxy::GetValue('__sort_' . $session . '_index_order__');
			if (!empty($oorder)) {
				$order = $oorder;
			}

			$ofield = SessionProxy::GetValue('__sort_' . $session . '_index_field__');
			if (!empty($ofield)) {
				$field = $ofield;
			}
		}
		$smarty = Registry::Get('smarty');
		$smarty->assign('tableSort', array($field, $order));
		return sprintf(' %s %s ', $field, $order);
	}

	/**
	 *
	 * @param string $base - zadany ciag
	 * @param string $string - szukany ciag na poczatku zadanego ciagu
	 */
	public static function TrimString($base, $string) {
		$cutLen = strlen($string);
		$trim = true;
		$done = $base;
		while ($trim) {
			$begStr = substr($done, 0, $cutLen);
			if ($string == $begStr) {
				$done = substr($done, $cutLen);
			} else {
				$trim = false;
			}
		}
		return $done;
	}

	function charset_utf_fix($string) {
		$utf_iso = array(
			"\xc4\x85" => "\xb1",
			"\xc4\x84" => "\xa1",
			"\xc4\x87" => "\xe6",
			"\xc4\x86" => "\xc6",
			"\xc4\x99" => "\xea",
			"\xc4\x98" => "\xca",
			"\xc5\x82" => "\xb3",
			"\xc5\x81" => "\xa3",
			"\xc3\xb3" => "\xf3",
			"\xc3\x93" => "\xd3",
			"\xc5\x9b" => "\xb6",
			"\xc5\x9a" => "\xa6",
			"\xc5\xba" => "\xbc",
			"\xc5\xb9" => "\xac",
			"\xc5\xbc" => "\xbf",
			"\xc5\xbb" => "\xaf",
			"\xc5\x84" => "\xf1",
			"\xc5\x83" => "\xd1",
			// xmlhttprequest uses different encoding
			"%u0104" => "\xA1",
			"%u0106" => "\xC6",
			"%u0118" => "\xCA",
			"%u0141" => "\xA3",
			"%u0143" => "\xD1",
			"%u00D3" => "\xD3",
			"%u015A" => "\xA6",
			"%u0179" => "\xAC",
			"%u017B" => "\xAF",
			"%u0105" => "\xB1",
			"%u0107" => "\xE6",
			"%u0119" => "\xEA",
			"%u0142" => "\xB3",
			"%u0144" => "\xF1",
			"%u00D4" => "\xF3",
			"%u015B" => "\xB6",
			"%u017A" => "\xBC",
			"%u017C" => "\xBF"
		);
		return str_replace(array_keys($utf_iso), array_values($utf_iso), $string);
	}

	public static function weekDay($month, $year, $current_day, $week_day_number=1) {

		$loop_start = $current_day - (date('N', mktime(0, 0, 0, $month, $current_day, $year)) - 1); //lets start loop from first day of week
		$loop_end = $current_day + (7 - (date('N', mktime(0, 0, 0, $month, $current_day, $year)))); //lets end loop to last day of week

		for ($i = $loop_start; $i <= $loop_end; $i++) {

			$day_of_the_week = date('N', mktime(0, 0, 0, $month, $i, $year)); //current day number 1-7 of week
			$loop_date = date('d', mktime(0, 0, 0, $month, $i, $year)); //current day in calendar
			if ($day_of_the_week == $week_day_number) {//if weekday number equals day number then lets return date
				return $loop_date;
			}
		}
	}

	/**
	 * Generuje ci�g znak�w
	 *
	 * @param string $length ilo�c znak�w
	 */
	function GetRandomString($length) {
		$string = md5(time());
		$string = substr($string, 0, $length);
		return($string);
	}

	function SQLFormat($sql) {
		$sqlForDisplay = $sql;
		$enter = "\n";
		$sqlForDisplay = str_replace('FROM', $enter . 'FROM', $sqlForDisplay);
		$sqlForDisplay = str_replace('INNER', $enter . 'INNER', $sqlForDisplay);
		$sqlForDisplay = str_replace('LEFT', $enter . 'LEFT', $sqlForDisplay);
		$sqlForDisplay = str_replace('WHERE', $enter . 'WHERE', $sqlForDisplay);
		$sqlForDisplay = str_replace('AND', $enter . 'AND', $sqlForDisplay);
		$sqlForDisplay = str_replace('GROUP', $enter . 'GROUP', $sqlForDisplay);
		$sqlForDisplay = str_replace('HAVING', $enter . 'HAVING', $sqlForDisplay);
		$sqlForDisplay = str_replace('ORDER', $enter . 'ORDER', $sqlForDisplay);
		$sqlForDisplay = str_replace('LIMIT', $enter . 'LIMIT', $sqlForDisplay);
		return $sqlForDisplay;
	}

	/**
	 * Z nazwy pola tabeli generuje nazwę zmiennej php
	 *
	 * @param string
	 */
	function SQLName2PHPName($name) {
		$wordsArray = explode('_', $name);
		//od 1 bo pierwszy element zostaje z małą literą
		for ($i = 1; $i < count($wordsArray); $i++) {
			$wordsArray[$i] = ucfirst($wordsArray[$i]);
		}
		return implode('', $wordsArray);
	}

	public static function Dictionary($keyword, $default = null) {

		$dictionaryArray = Registry::Get("dictionary");
		if (isset($dictionaryArray[$keyword]))
		{
			return $dictionaryArray[$keyword];
		}
		else if ($default != null)
			return $default;
		else
			return $keyword;
	}

	public static function Translate($label,$user,$param = array(),$mode ="t")
	{
		if($mode == "t")
		{
			if(SessionProxy::GetValue('translate') == "true" && is_object($user) && $user->hasRole('editor'))
				return '<span style="border:1px dotted white" translate="true" translateurl="' . Router::GenerateUrl('dictionaryEditPopover', array('key' => urlencode($label))) . '">' . MfDictionaryDAL::RegistryTranslate($label,$param) . '</span>';
			else
				return MfDictionaryDAL::RegistryTranslate($label,$param);
		}
		else
		{
			if(SessionProxy::GetValue('translate') == "true" && is_object($user) && $user->hasRole('editor'))
				return MfDictionaryDAL::RegistryTranslate($label,$param) . '"' . 'translate="true" translateurl="' .  Router::GenerateUrl('dictionaryEditPopover', array('key' => urlencode($label))) . '" style="border:1px dotted white;';
			else
				return MfDictionaryDAL::RegistryTranslate($label,$param);
		}
	}

	public static function Filter() {

		if (Request::IsPost()) {
			$post = Request::GetAllPost();

			$filter = $post['filter'];

			SessionProxy::GetAndSetValue('filter', $post['filter']);
		} else {
			if (SessionProxy::IsSetValue('filter')) {
				$filter = SessionProxy::GetValue('filter');
			} else {
				$filter = 3;
			}
		}

		return $filter;
	}

	public static function PerPage(&$smarty = null) {

		if (Request::IsPost() && Request::Check('perPage') ) {
			$post = Request::GetAllPost();
			$perPage = SessionProxy::GetAndSetValue('perPage', $post['perPage']);
			
		} else {
			if (SessionProxy::IsSetValue('perPage')) {
				$perPage = SessionProxy::GetValue('perPage');
			} else {
				$perPage = CONTENT_PER_PAGE;
			}
		}
		if($perPage == 0)
			$perPage = CONTENT_PER_PAGE;
		if ($smarty != null)
			$smarty->assign('perPage', $perPage);
		return $perPage;
	}

	public static function Sort(&$param, &$smarty = null) {
		if (isset($param[ROUTER_SORT_LABEL]) && $param[ROUTER_SORT_LABEL] && isset($param[ROUTER_DIR_LABEL]) && $param[ROUTER_DIR_LABEL]) {

			$sortBy = $param[ROUTER_SORT_LABEL];
			$sortDir = $param[ROUTER_DIR_LABEL];

			$sortByArray = explode('-', $sortBy);
			$sortDirArray = explode('-', $sortDir);


			if ($smarty != null) {
				$smarty->assign('_sortBy', $sortByArray);
				$smarty->assign('_sortDir', $sortDirArray);
			}

			if (count($sortByArray) >= 1 && count($sortDirArray) == count($sortByArray)) {
				$sortBy = $sortByArray;
				$sortDir = $sortDirArray;
			} else {
				throw new CoreException('Sortowanie: błędna ilość parametrów');
			}
		} else {

			$sortBy = array();
			$sortDir = array();
			$param[ROUTER_SORT_LABEL] = "";
			$param[ROUTER_DIR_LABEL] = "";
		}

		return array($sortBy, $sortDir);
	}

	public static function Page(&$param, &$smarty = null) {
		if (isset($param[ROUTER_PAGE_LABEL]) ) {

			$pageNum = $param[ROUTER_PAGE_LABEL];
			$page = explode('-', $pageNum);

			array_filter($page, create_function('$x', 'if ((int)$x <= 0) { throw new UserException("Strona poza zakresem"); }'));
			
			if ($smarty != null)
				$smarty->assign('_page', $page);
		} else {
			$page = array();
			$param[ROUTER_PAGE_LABEL] = null;
		}
		return $page;
	}

	public static function Money($val) {
		$val = round($val,2);
		return sprintf("%.2F", $val);
	}
	
	public static function GetNowDate() {
		return date("Y-m-d H:i:s");
	}
	
	public static function FileOutput($file,$name,$mime_type = ''){
		if(!is_readable($file)) die('File not found or inaccessible!');
 
		 $size = filesize($file);
		 $name = rawurldecode($name);
		 
		 /* Figure out the MIME type (if not specified) */
		 $known_mime_types=array(
		 	"pdf" => "application/pdf",
		 	"txt" => "text/plain",
		 	"html" => "text/html",
		 	"htm" => "text/html",
			"exe" => "application/octet-stream",
			"zip" => "application/zip",
			"doc" => "application/msword",
			"xls" => "application/vnd.ms-excel",
			"ppt" => "application/vnd.ms-powerpoint",
			"gif" => "image/gif",
			"png" => "image/png",
			"jpeg"=> "image/jpg",
			"jpg" =>  "image/jpg",
			"php" => "text/plain"
		 );
		 
		 if($mime_type=='' || is_null($mime_type)){
			 $file_extension = strtolower(substr(strrchr($file,"."),1));
			 if(array_key_exists($file_extension, $known_mime_types)){
				$mime_type=$known_mime_types[$file_extension];
			 } else {
				$mime_type="application/force-download";
			 };
		 };
		 
//		 @ob_end_clean(); //turn off output buffering to decrease cpu usage
		 
		 // required for IE, otherwise Content-Disposition may be ignored
		 if(ini_get('zlib.output_compression'))
		  ini_set('zlib.output_compression', 'Off');
		 
		 header('Content-Type: ' . $mime_type);
		 header('Content-Disposition: attachment; filename="'.$name.'"');
		 header("Content-Transfer-Encoding: binary");
		 header('Accept-Ranges: bytes');
		 
		 /* The three lines below basically make the 
		    download non-cacheable */
		 header("Cache-control: private");
		 header('Pragma: private');
		 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		 
		 // multipart-download and download resuming support
		 if(isset($_SERVER['HTTP_RANGE']))
		 {
			list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
			list($range) = explode(",",$range,2);
			list($range, $range_end) = explode("-", $range);
			$range=intval($range);
			if(!$range_end) {
				$range_end=$size-1;
			} else {
				$range_end=intval($range_end);
			}
		 
			$new_length = $range_end-$range+1;
			header("HTTP/1.1 206 Partial Content");
			header("Content-Length: $new_length");
			header("Content-Range: bytes $range-$range_end/$size");
		 } else {
			$new_length=$size;
			header("Content-Length: ".$size);
		 }
		 
		 /* output the file itself */
		 $chunksize = 1*(1024*1024); //you may want to change this
		 $bytes_send = 0;
		 if ($file = fopen($file, 'r'))
		 {
			if(isset($_SERVER['HTTP_RANGE']))
			fseek($file, $range);
		 
			while(!feof($file) && 
				(!connection_aborted()) && 
				($bytes_send<$new_length)
			      )
			{
				$buffer = fread($file, $chunksize);
				print($buffer); //echo($buffer); // is also possible
				flush();
				$bytes_send += strlen($buffer);
			}
		 fclose($file);
		 } else die('Error - can not open file.');
		 
	}
	
	/**
	 * Obsługa headerów
	 */
	public static function AddHeader($name, $value, $overwrite = false) {
		$headers = Registry::Get('headers');
		//$headers[$name][] = $value;
		if(!isset($headers[$name]))$headers[$name] = array();

		//obsługa overWrite dla wartości
		/*if(is_array($value) && isset($value['name']) && isset($value['content'])) {
			if(isset($headers[$name][$value['name']]) && isset($headers[$name]['content']) && $overwrite) {
				$headers[$name][$value['name']]['content'] = $value['content'];
			}elseif(isset($headers[$name][$value['name']]) && isset($headers[$name]['content']) && !$overwrite) {
				$headers[$name][$value['name']]['content'] .= $value['content'];
			}else{
				$headers[$name][] = $value;
			}
			
		}else{
			$headers[$name][] = $value;		
		}*/
		
		//Nowa obsługa która uniemożliwia nadpisywanie/dopisywanie w nieskońćzoność danych
		if(is_array($value)) {
			if(isset($value['content']) && $name == 'meta') {
				$t = $value;
				if(isset($t['content']))unset($t['content']);
				$label = implode('-',$t);
				
				if(!$overwrite) {
					$headers[$name][$label] = array_merge($value,array('content' => (isset($headers[$name][$label]['content'])?$headers[$name][$label]['content']:'').' '.$value['content']));
				}else{
					$headers[$name][$label] = $value;
				}
			}else if(isset($value['href']) && $name == 'link') {
				$label = $value['href'];
				if($overwrite) {
					$headers[$name] = array($label => $value);
				}else{
					$headers[$name][$label] = $value;
				}
			}else{
				if($overwrite)
					$headers[$name] = array($value);
				else
					$headers[$name][] = $value;
			}
		}elseif(!is_null($value)){
			if($overwrite)
					$headers[$name] = array($value);
				else
					$headers[$name][] = $value;
		}

		Registry::Remove('headers');
		Registry::Set('headers', $headers);
	}

	public static function cr2pln($cr) {
		$cr2pln = floatval(Registry::get('credit_to_pln'));
		return sprintf("%01.2f",$cr2pln * $cr);
	}
}
